import { _decorator, Camera, Component, EventTouch, instantiate, Node, UITransform, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GridMap')
export class GridMap extends Component {
    @property(Node)
    cell : Node = null;
    @property(Camera)
    camera : Camera = null;

    outerRadius : number = 100;
    innerRadius : number = this.outerRadius * 0.866025404;
    start() {
        for(let i = 0; i < 10; i++) {
            for(let j = 0; j < 10; j++) {
                let cell = instantiate(this.cell);
                cell.setPosition(this.cell2Pos(i, j));
                this.node.addChild(cell);
            }
        }

        this.node.on(Node.EventType.TOUCH_START, this.onTouchstart, this);
    }

    onTouchstart(et : EventTouch){
        let tPos = et.getLocation();
        let spos = new Vec3(tPos.x,tPos.y,0);
        let wpos = new Vec3();
        this.camera.screenToWorld(spos,wpos)
        this.node.getComponent(UITransform).convertToNodeSpaceAR(wpos, spos);
        console.log("touch local pos =>",spos);
    }

    cell2Pos(x:number, y:number) : Vec3 {
        let v3 = new Vec3();
        let offsety = x % 2 == 0? 0 : this.innerRadius;
        v3.x = x * this.outerRadius * 1.5;
        v3.y = y * this.innerRadius * 2 + offsety;
        return v3;
    }

    pos2Cell(pos:Vec3) : Vec2 {
        let x = pos.x / (this.outerRadius * 1.5);
        let offsety = x % 2 == 0? 0 : this.innerRadius;
        let y = (pos.y - offsety) / (this.innerRadius * 2);
        return new Vec2(Math.floor(x), Math.floor(y));
    }
}


